<template>
  <h2 align="center">护理项目列表</h2>
  <el-form :inline="true" :model="queryFrom">
    <el-form-item label="名称">
      <el-input v-model="queryFrom.name" placeholder="请输入名称" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="queryAll">查询</el-button>
      <el-button type="default" @click="clearForm">清空</el-button>
    </el-form-item>
  </el-form>
  <el-button type="primary" plain @click="add"> + 新增</el-button>
  <el-button type="danger" plain @click="deleteNursingByIds"> - 删除</el-button>
  <!-- 弹窗 -->
  <div>
    <!-- 添加或修改护理项目对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="nursingProjectRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="排序号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入排序号" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <el-upload class="avatar-uploader" action="/api/upload" :headers="{ 'token': token }" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="form.image" :src="form.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="护理要求" prop="nursingRequirement">
          <el-input v-model="form.nursingRequirement" placeholder="请输入护理要求" />
        </el-form-item>
        <el-form-item label="状态" prop="remark">
          <el-input v-model="form.status" placeholder="请输入状态(0禁用,1启用)" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!-- 表格 -->
  <div>
    <br />
    <el-table :data="formData" @selection-change="handleSelectionChange">
      <!-- :selectable="selectable" 复选框要写 -->
      <el-table-column fixed="left" type="selection" width="55" />
      <el-table-column type="index" prop="id" label="编号" align="center" width="66" />
      <el-table-column prop="name" label="名称" align="center" width="150" />
      <el-table-column prop="orderNo" label="排序号" align="center" width="150" />
      <el-table-column prop="unit" label="单位" align="center" width="150" />
      <el-table-column prop="price" label="价格" align="center" width="150" />
      <el-table-column prop="image" label="图片" align="center" width="150">
        <template #default="scope">
          <img :src="scope.row.image" width="50px" height="50px" />
        </template>
      </el-table-column>
      <el-table-column prop="nursingRequirement" label="护理要求" align="center" width="150" />
      <el-table-column prop="status" label="状态" align="center" width="150">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
          <el-tag v-else type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center" width="150" />
      <el-table-column prop="updateTime" label="更新时间" align="center" width="150" />
      <el-table-column fixed="right" label="操作" align="center" width="180">
        <template #default="scope">
          <el-button type="primary" @click="handleEdit(scope.row)" small link>编辑</el-button>
          <el-button type="danger" @click="handleDelete(scope.row)" small link>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 分页 -->
  <br />
  <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
    layout="total, sizes, prev, pager, next, jumper" :total="total" background=true @size-change="handleSizeChange"
    @current-change="handleCurrentChange" />
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import { queryAllPage, addNursing, queryById, updateNursing, deleteNursing } from '@/api/nursingProject'
import { userStore } from '@/stores/loginStore'
import { Plus } from '@element-plus/icons-vue'
import { id } from 'element-plus/es/locales.mjs';
const userInfo = userStore()
let token = ref('')

const formData = ref([])
const total = ref(0)
const queryFrom = reactive({
  name: ''
})
const currentPage = ref(1)
const pageSize = ref(5)
const queryAll = async () => {
  const res = await queryAllPage(queryFrom.name, currentPage.value, pageSize.value)
  formData.value = res.data.rows
  total.value = res.data.total
}
// 清空表单
const clearForm = () => {
  queryFrom.name = ''
  queryAll()
}
const form = ref({
  id: '',
  name: '',
  orderNo: '',
  unit: '',
  price: '',
  image: '',
  nursingRequirement: '',
  status: 0
})
const nursingProjectRef = ref()
const title = ref('')
const open = ref(false)
const rules = reactive({
  name: [
    { required: true, message: '名称不能为空', trigger: 'blur' },
    { min: 3, max: 10, message: '长度3-10', trigger: 'blur' },
  ]
})
// 分页
const handleSizeChange = (val: number) => {
  currentPage.value = 1
  pageSize.value = val
  queryAll()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  queryAll()
}
// 多选
const ids = ref<string[]>([])
const name = ref('')
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.id)
  name.value = selection.map((item: any) => item.name)
  // console.log(ids.value);
}
const deleteNursingByIds = () => {
  ElMessageBox.confirm('确定要删除姓名为: ' + name.value + '的员工吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const idStr = ids.value.join(',')
    let result = await deleteNursing(idStr)
    if (result.code) {
      ElMessage.success('删除成功！')
      queryAll()
    } else {
      ElMessage.success('删除失败！')
      queryAll()
    }
  }).catch(() => {
    ElMessage.info('取消删除')
  })
}
//单个删除员工
const handleDelete = async (row: any) => {
  // console.log("删除", row);
  ids.value = [row.id]
  name.value = row.name
  deleteNursingByIds()
}
// 添加
const add = () => {
  open.value = true
  title.value = '添加项目'
  // 清空表单
  form.value = {
    id: '',
    name: '',
    orderNo: '',
    unit: '',
    price: '',
    image: '',
    nursingRequirement: '',
    status: 0
  }
}
const submitForm = async () => {
  if (!nursingProjectRef) return
  await nursingProjectRef.value.validate(async (valid: any, fields: any) => {
    let res = null
    if (valid) {
      if (form.value.id) {
        res = await updateNursing(form.value)
        if (res.code) {
          ElMessage.success("修改成功")
          queryAll()
          open.value = false
        } else {
          ElMessage.error("修改失败")
        }
      } else {
        res = await addNursing(form.value)
        if (res.code) {
          ElMessage.success("新增成功")
          queryAll()
          open.value = false
        } else {
          ElMessage.error("新增失败")
        }
      }
      // console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}
const cancel = () => {
  open.value = false
}
// 图片上传
//上传成功后调用的方法
const handleAvatarSuccess = (
  response: any,
  uploadFile: any,
) => {
  form.value.image = response.data
}
//上传前校验
const beforeAvatarUpload = (rawFile: File) => {
  if (rawFile.type !== 'image/png') {
    ElMessage.error('图片格式必须是 png 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不得超过 2MB!')
    return false
  }
  return true
}

onMounted(() => {
  token.value = userInfo.token
  queryAll()
})
const handleEdit = async (row: any) => {
  open.value = true
  title.value = "编辑项目"
  let result = await queryById(row.id)
  form.value = result.data
  console.log("编辑", row);
}

</script>
<style scoped>
/* 头像上传样式 */
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>